package com.lwphk.easydocs.core.parameter.parse;

import java.lang.reflect.Array;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.RequestBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lwphk.easydocs.core.ParameterParseAbstract;
import com.lwphk.easydocs.core.vo.ContentType;
import com.lwphk.easydocs.core.vo.MethodInfo;
import com.lwphk.easydocs.core.vo.ParamInfo;
import com.lwphk.easydocs.util.ClassTypeUtil;

public class ArrayParameterHandler extends ParameterParseAbstract {

	@Override
	public void parse(Parameter parameter, MethodInfo mi) throws Exception {
		Class<?> parameterType = parameter.getType();
		Class<?> realClass = parameterType.getComponentType();
		while(realClass.isArray()) {
			realClass = realClass.getComponentType();
		}
		
		if(ClassTypeUtil.isPrimitive(realClass)) {
			ParamInfo pi = buildBasicInfo(parameter);
			pi.setType(realClass.getSimpleName()+"[]");
			
			
			RequestBody requestBody = parameter.getAnnotation(RequestBody.class);
			if (requestBody != null) {
				pi.setName("");
				mi.setContentType(ContentType.JSON);
				mi.setBodyVal(JSON.toJSONString(Array.newInstance(realClass, 2),
						SerializerFeature.WRITE_MAP_NULL_FEATURES));
				mi.getBodyParams().add(pi);
			}else {
				mi.getQueryParams().add(pi);
			}
			
		}else {
			List<ParamInfo> list  = getObjFields(realClass);
			
			RequestBody requestBody = parameter.getAnnotation(RequestBody.class);
			if (requestBody != null) {
				mi.setContentType(ContentType.JSON);
				
				mi.setBodyVal(JSON.toJSONString(Arrays.asList(realClass.newInstance()),
						SerializerFeature.WRITE_MAP_NULL_FEATURES));
				
				
				mi.getBodyParams().addAll(list);
				
			}else {
				mi.getQueryParams().addAll(list);
			}
			
			
		}
			
		
		
	}

}
